#include "p33Fxxxx.h"
#include "dsp.h"

// External Oscillator
_FOSCSEL(FNOSC_FRC);					
_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF  & POSCMD_XT);	// Clock Switching is enabled and Fail Safe Clock Monitor is disabled
													// OSC2 Pin Function: OSC2 is Clock Output
													// Primary Oscillator Mode: XT Crystanl



_FWDT(FWDTEN_OFF); 						            // Watchdog Timer Enabled/disabled by user software
													// (LPRC can be disabled by clearing SWDTEN bit in RCON register
_FPOR(FPWRT_PWR1);  					 			// Turn off the power-up timers.
_FGS(GCP_OFF);            							// Disable Code Protection



/* Constant Definitions */
#define BLOCK_LENGTH    1024           				/*We will filter a block of 1024 samples in this example*/
#define LOWPASSFILTER           					/*<---Comment out this line of the code if BPF is desired */


/* Extern definitions for the imported *.s files from dsPICWorks */

extern fractional pasab[1024];        			/* Input Array containing Square wave signal */
                                        			/* of frequency 80 Hz sampled at 11000 Hz*/

/* extern definitions for the imported *.s files from dsPIC Filter Design */

extern FIRStruct pasabajoFilter;  					/*Contains filter structures for FIR-LPF*/


/* Filter Operation Vectors */
fractional FilterOut[BLOCK_LENGTH] ;    			/*Output array where filtered output will*/
                                        			/*be stored */


int main(void) {

// Configure Oscillator to operate the device at 40Mhz
// Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
// Fosc= 11M*40/(2*2)=110Mhz for 11M input clock
	PLLFBD=38;					// M=40
	CLKDIVbits.PLLPOST=0;		// N1=2
	CLKDIVbits.PLLPRE=0;		// N2=2
	OSCTUN=0;					// Tune FRC oscillator, if FRC is used

// Disable Watch Dog Timer
	RCONbits.SWDTEN=0;

// Clock switch to incorporate PLL
	__builtin_write_OSCCONH(0x03);		// Initiate Clock Switch to Primary
										// Oscillator with PLL (NOSC=0b011)
	__builtin_write_OSCCONL(0x01);		// Start clock switching
	while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur	

// Wait for PLL to lock
	while(OSCCONbits.LOCK!=0) {};

        /* FILTER OPERATIONS */
        

                /*Initialize the filter state variables (delay line) prior to calling */
                /*the FIR() routine the very first time */

                        FIRDelayInit(&pasabajoFilter);

                /* Perform FIR Low Pass filtering on a square wave of frequency 80 Hz    */

                        FIR(BLOCK_LENGTH,&FilterOut[0],&pasab[0],&pasabajoFilter);
              

        while (1);
}
